package com.edais.actions;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yunzhi.domain.RequestHeader;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import com.yunzhi.util.RequestUtil;
import com.yunzhi.util.ResponseUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.edais.domain.AgreementMirror;
import com.edais.service.CenterService;
import com.edais.service.EPlanAssignService;
import com.edais.service.FinancePlanOpfService;
import com.edais.service.WalletService;
import com.edais.util.ActionException;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.FastDFSUtil;
import com.edais.util.JsonUtil;
import com.edais.util.Message;

@Controller
@RequestMapping("/wallet")

public class WalletAction  implements Serializable{
	private static final Log logger = LogFactory.getLog(WalletAction.class);

	@Autowired
	private WalletService walletService;
	@Autowired
	private FastDFSUtil fastDFSUtil;
	@Autowired
	private CenterService centerService;
	@Autowired
	private FinancePlanOpfService financeService;
	
	@Autowired
	private EPlanAssignService assignService;
	
/**
	 * E400014 我的钱包统计信息
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getStatisticsInfor")
	public void getStatisticsInfor(HttpServletRequest request,
			HttpServletResponse response) {
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId"); // 用户id

		if (StringUtils.isBlank(userId)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			logger.debug("/wallet/getStatisticsInfor 传入参数为空-----userId");
			return;
		}

		try {
			String transCode = "E330001";
			// 设置报文体报文数据
			Map<String, Object> pageModelForWallet = new HashMap<String, Object>();

			pageModelForWallet.put("userId", userId); // 用户id
			// TODO 获取手机支持的产品id字符串
			// 该接口已暂停调用
			// 产品类型：101 e计划(90天)，102 e贷通，103 涨薪宝, 104 e计划(365天),多个产品之间用英文【,】进行分隔
			//pageModelForWallet.put("productType", "101,103,104");
			String financeIdString = financeService.getFinanceString();
			pageModelForWallet.put("productType", financeIdString);
			
			// 构建json字符串
			String jsonStr = CommonUtil.constructJsonStr(transCode, userId,
					pageModelForWallet);

			// 调用核心接口E320001我的钱包统计信息
			String result = this.walletService.getStatisticsInfor(jsonStr);

			// 处理返回结果
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			logger.debug("/wallet/getStatisticsInfor E320001 异常-----"
					+ e.getMessage());

			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
		return;
	}

	/**
	 * E400015 我的钱包下期回款信息
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getNextIncomeInfor")
	public void getNextIncomeInfor(HttpServletRequest request,
			HttpServletResponse response) {
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId"); // 用户id

		if (StringUtils.isBlank(userId)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			logger.debug("/wallet/getNextIncomeInfor 传入参数为空-----userId");
			return;
		}

		try {
			String transCode = "E330002";
			// 设置报文体报文数据
			Map<String, Object> pageModelForWallet = new HashMap<String, Object>();

			pageModelForWallet.put("userId", userId); // 用户id
			// TODO 获取手机支持的产品id字符串
			// 该接口已暂停调用
			// 产品类型：101 e计划(90天)，102 e贷通，103 涨薪宝, 104 e计划(365天),多个产品之间用英文【,】进行分隔
			//pageModelForWallet.put("productType", "101,103,104");
			String financeIdString = financeService.getFinanceString();
			pageModelForWallet.put("productType", financeIdString);

			// 构建json字符串
			String jsonStr = CommonUtil.constructJsonStr(transCode, userId,
					pageModelForWallet);

			// 调用核心接口E320002我的钱包下期回款信息
			String result = this.walletService.getNextIncomeInfor(jsonStr);

			// 处理返回结果
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			logger.debug("======异常发生======");
			logger.debug("======/wallet/getNextIncomeInfor E320002======");

			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}

		return;
	}

	/**
	 * 1.x版本：E400016 已购买订单列表
	 * 2.0版本：E500030已购买订单列表
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getPurchaseDetailList")
	public void getPurchaseDetailList(HttpServletRequest request,
			HttpServletResponse response) {
		Integer current = 0;
		Integer pageSize = 10;//默认显示10条

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId"); // 用户id
		String currentStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME); // 当前页数
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME); // 页大小

		//获取排序条件orderCondition
		String orderCondition = "0";//paramsMap.get("orderCondition");
		String productType = "";//paramsMap.get("productType");//产品类型，作为查询条件
		//订单状态：1.签约中、2.回款中、4.已退出、0.全部
		String orderState = paramsMap.get("orderState");
		
		if (StringUtils.isBlank(userId)) { // 用户id为空
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			logger.debug("/wallet/getPurchaseDetailList 传入参数为空-----userId");
			return;
		}

		try {
			// 传入理财产品id为空，取手机支持的所有产品
			if (StringUtils.isBlank(productType)) {
				productType = this.assignService.getAllProductType();
			}
			//分页参数
			if (currentStr != null && !("".equals(currentStr))) {
				current = Integer.parseInt(currentStr);
			}
			if (pageSizeStr != null && !("".equals(pageSizeStr))) {
				pageSize = Integer.parseInt(pageSizeStr);
			}

			//调用核心【E330003已购买订单列表(产品扩展，时间金额排序)】接口
			String transCode = "E330020";
			// 设置报文体报文数据
			Map<String, Object> pageModelForWallet = new HashMap<String, Object>();

			pageModelForWallet.put("userId", userId); // 用户id
			//pageModelForWallet.put("productType", Consts.GQB); 
			// 产品类型：101 e计划(90天)，102 e贷通，103 涨薪宝, 104 e计划(365天),多个产品之间用英文【,】进行分隔
			pageModelForWallet.put("productType", productType);
			pageModelForWallet.put("orderCondition", orderCondition);
			//订单状态：1.签约中、2.回款中、4.已退出、0.全部
			pageModelForWallet.put("orderState", orderState);
			
			pageModelForWallet.put("orderId", ""); // 订单id
			pageModelForWallet.put("current", current); // 当前页
			pageModelForWallet.put("pageSize", pageSize); // 页大小

			// 构建json字符串
			String jsonStr = CommonUtil.constructJsonStr(transCode, userId,
					pageModelForWallet);

			// 调用核心【E330020已购买订单列表(产品扩展，时间金额排序)】接口
			String result = this.walletService.getPurchaseDetail(jsonStr);

			// 处理返回结果
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("======异常发生======");
			logger.debug("======/wallet/getPurchaseDetailList E330020======");

			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}

		return;
	}

	/**
	 * E400017 债权列表
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getCreditList")
	public void getCreditList(HttpServletRequest request,
			HttpServletResponse response) {
		Integer current = 1;
		Integer pageSize = 1000;//默认显示1000条

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String orderId = paramsMap.get("orderId"); // 计划编号(订单id)
		String currentStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME); // 当前页数
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME); // 页大小

		if (StringUtils.isBlank(orderId)) { // 订单id为空
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("/wallet/getCreditList 传入参数为空-----orderId");
			return;
		}

		try {
			if (currentStr != null && !("".equals(currentStr))) {
				current = Integer.parseInt(currentStr);
			}
			if (pageSizeStr != null && !("".equals(pageSizeStr))) {
				pageSize = Integer.parseInt(pageSizeStr);
			}

			String transCode = "E320004";
			// 设置报文体报文数据
			Map<String, Object> pageModelForWallet = new HashMap<String, Object>();

			pageModelForWallet.put("orderId", orderId); // 订单id
			//TODO 获取手机支持的产品id字符串
			//根据订单进行查询，订单已经是手机支持的产品
			//pageModelForWallet.put("productType", Consts.GQB); // 产品类型：103（鼓钱包）
			//String financeIdString = financeService.getFinanceString();
			//pageModelForWallet.put("productType", financeIdString); // 产品类型字符串
			pageModelForWallet.put("current", current); // 当前页
			pageModelForWallet.put("pageSize", pageSize); // 页大小

			// 构建json字符串
			String jsonStr = CommonUtil.constructJsonStr(transCode, "",
					pageModelForWallet);

			// 调用核心接口
			String result = this.walletService.getCreditDetail(jsonStr);

			// 处理返回结果
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			logger.debug("======异常发生======");
			logger.debug("======/wallet/getCreditList E320004======");

			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}

		return;
	}

	/**
	 * E400018 收款详情列表
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getRepaymentDetailList")
	public void getRepaymentDetailList(HttpServletRequest request,
			HttpServletResponse response) {
		Integer current = 0;
		Integer pageSize = 0;

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId"); // 用户ID
		String creditId = paramsMap.get("creditId"); // 债权id
		String currentStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME); // 当前页数
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME); // 页大小

		// 用户id为空 或者 债券id为空
		if (StringUtils.isBlank(userId) || StringUtils.isBlank(creditId)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("/wallet/getRepaymentDetailList 传入参数为空-----userId or creditId");
			return;
		}

		try {
			if (currentStr != null && !("".equals(currentStr))) {
				current = Integer.parseInt(currentStr);
			}
			if (pageSizeStr != null && !("".equals(pageSizeStr))) {
				pageSize = Integer.parseInt(pageSizeStr);
			}

			//1.0时，调用核心接口 E300020我的收款分期明细;1.5时，调用新核心接口 E330010 收款详情列表
			String transCode = "E330010";//"E300020";
			// 设置报文体报文数据
			Map<String, Object> pageModelForWallet = new HashMap<String, Object>();

			pageModelForWallet.put("userId", userId); // 用户ID
			pageModelForWallet.put("creditCId", creditId); // 债权id
			//pageModelForWallet.put("bId", ""); // 标的id
			pageModelForWallet.put("current", current); // 当前页数
			pageModelForWallet.put("pageSize", pageSize); // 页大小

			// 构建json字符串
			String jsonStr = CommonUtil.constructJsonStr(transCode, userId,
					pageModelForWallet);

			// 调用核心接口E300020取得我的收款分期明细
			String result = this.walletService.getRepaymentDetail(jsonStr);

			// 处理返回结果
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			logger.debug("======异常发生======");
			logger.debug("======/wallet/getRepaymentDetailList E300020======");

			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}

		return;
	}

	/**
	 * E400019 资金流水
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getFundFlowList")
	public void getFundFlowList(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}
		RequestHeader header = RequestUtil.decodeHeader(request);
		Map map = RequestUtil.decodeData(request);

		Integer current = 0;
		Integer pageSize = 10;
		String currentStr = String.valueOf(map.get(Consts.Page.PAGE_CURRENT_NAME)); // 当前页数
		String pageSizeStr = String.valueOf(map.get(Consts.Page.PAGE_SIZE_NAME)); // 页大小
		String inOrOut = String.valueOf(map.get("inOrOut"));//抽取条件（无值--全部、in--收入、out--支出）
		String userId=String.valueOf(header.getUserId());

		if (currentStr != null && !("".equals(currentStr))) {
			current = Integer.parseInt(currentStr);
		}
		if (pageSizeStr != null && !("".equals(pageSizeStr))) {
			pageSize = Integer.parseInt(pageSizeStr);
		}

		String transCode = "E330004";
		// 设置报文体报文数据
		Map<String, Object> pageModelForWallet = new HashMap<String, Object>();

		pageModelForWallet.put("userId", userId); // 用户id
		// TODO 获取手机支持的产品id字符串
		String financeIdString = financeService.getFinanceString();
		pageModelForWallet.put("productType", financeIdString);
		pageModelForWallet.put("current", current); // 当前页
		pageModelForWallet.put("pageSize", pageSize); // 页大小

		if(!StringUtils.isBlank(inOrOut)){
			pageModelForWallet.put("inOrOut", inOrOut);////抽取条件（无值--全部、in--收入、out--支出）
		}else{
			pageModelForWallet.put("inOrOut", "");////抽取条件（无值--全部、in--收入、out--支出）
		}
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, userId, pageModelForWallet);

		// 调用核心接口E330004取得资金流水详情
		ResultDTO result = this.walletService.getFundFlowDetail(jsonStr,current,pageSize);
		ResponseUtil.write(response,  result);
		return;
	}	
	
	/**
	 * 查看合同(理财人)
	 * @param request
	 * @return
	 * @throws ActionException
	 */
	@RequestMapping(value = "/checkTheContract")
	public void checkTheContract(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String data = "";
	
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");        //用户ID
		String creditAcctCid = paramsMap.get("creditAcctCid");//债权编号
		
		// 用户id 或 债券编号 为空
		if (StringUtils.isBlank(userId) || StringUtils.isBlank(creditAcctCid)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			logger.debug("/wallet/checkTheContract 传入参数为空-----userId或者creditAcctCid");
			return;
		}
		try{
			String transCode = "E330016";
//			String agreementUrl = null;
			String agreementUrl = "";
			Map<String, Object> mapOrderList = new HashMap<String, Object>();
			mapOrderList.put("creditId", creditAcctCid);//债权子户ID
			
			Map resMap = this.centerService.coreUse(userId, transCode, mapOrderList);
			if (resMap != null && "00000".equals(resMap.get("rescode"))) {
				List<Map<String, Object>> list = JsonUtil.toList(resMap.get("list"));
			
				for (int i = 0; i < list.size(); i++) {
					Map tmp = list.get(i);
//					agreementUrl = String.valueOf(tmp.get("AGREEMENT_URL"));
					agreementUrl = (null == tmp.get("AGREEMENT_URL"))? "":tmp.get("AGREEMENT_URL").toString();
					break;
				}
			} else {
				logger.error("/wallet/checkTheContract 异常" + resMap.get("resmsg"));
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}
			
			if(null == agreementUrl||"".equals(agreementUrl)||"".equals(agreementUrl.trim()) 
				|| "null".equals(agreementUrl)){
				AgreementMirror temp = new AgreementMirror();
				temp.setReceive_user_id(Integer.parseInt(userId));
				temp.setAgreement_type("LOANAGREEMENT_INVEST");//默认借款协议-出借人版本
				temp.setReceive_plan_subpoint_id(creditAcctCid);
				//查询合同镜像
				AgreementMirror domain = this.walletService.getAgreementMirrorByCons(temp);
				if(domain!=null){
					agreementUrl = domain.getUrl();
				}
			}
			
			if(null == agreementUrl||"".equals(agreementUrl)||"".equals(agreementUrl.trim())){
				data = new String("合同为空");
			}else{
				byte[] buf=this.fastDFSUtil.download(agreementUrl);
				if(buf == null){
					logger.debug("======查看合同异常发生======");
					logger.debug("======/wallet/checkTheContract ======");
					String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), 
						Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
					// 处理返回结果
					CommonUtil.responseJsonNotEncrypt(result, response);
					return;
				}else{
					logger.debug("/wallet/checkTheContract 合同路径为：" + agreementUrl);
					data = new String(buf,"UTF8");
				}
			}
			jsonMap.put("agreement", data);
			logger.debug("/wallet/checkTheContract 合同内容：" + data);
			String result = CommonUtil.setResultStringCn(jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
		}catch(Exception e){
			logger.error("/wallet/checkTheContract 异常" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
	}
	
	/**
	 * Q310002资金流水 详情
	 * 根据流水号flowId和交易流水号transFlowNo  获得流水明细
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getFundFlowDetail")
	public void getFundFlowDetail(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}
		Map map = RequestUtil.decodeData(request);
		String flowId = String.valueOf(map.get("flowId")); // 流水号
		String transFlowNo = String.valueOf(map.get("transFlowNo"));//交易流水号
		String loginfo="根据流水号flowId="+flowId+"和交易流水号transFlowNo=" +transFlowNo+"获得流水明细接口/wallet/getFundFlowDetail";

		String transCode = "Q310002";
		String jsonStr = CommonUtil.constructJsonStr(transCode, "", map);
		// 调用核心接口Q310002取得资金流水详情
		ResultDTO result = this.walletService.getFundFlowDetail(jsonStr,loginfo);
		ResponseUtil.write(response,  result);
		return;
	}	
	
}
